/**
 * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr)
 * This file is part of CSipSimple.
 *
 *  CSipSimple is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  If you own a pjsip commercial license you can also redistribute it
 *  and/or modify it under the terms of the GNU Lesser General Public License
 *  as an android library.
 *
 *  CSipSimple is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with CSipSimple.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.cloudptt.api.product.log;

import java.io.File;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.device.PNC460;
import com.cloudptt.api.product.device.PNC550;
import com.cloudptt.api.product.device.PNC560;

import android.os.Environment;
import de.mindpipe.android.logging.log4j.LogConfigurator;

public class Log {
	private final static String THIS_FILE = "Log";
	private static volatile int logLevel = 6;
	
	
	protected static Logger log=Logger.getLogger("");  
	/**
	 * Change current logging level
	 * @param level new log level 1 <= level <= 6 
	 */
	public static void setLogLevel(int level) {
		if(!Product.mPermissonGrant){
			android.util.Log.e("["+"log"+"] ", "setLogLevel level = " + level);
		}else{
			log.error("["+"log"+"] "+"setLogLevel level = " + level);
		}
		logLevel = level;
	}
	
	/**
	 * Get the current log level
	 * @return the log level
	 */
	public static int getLogLevel() {
	    return logLevel;
	}
	

	
	/**
	 * Log verbose
	 * @param tag Tag for this log
	 * @param msg Msg for this log
	 */
	public static void v(String tag, String msg) {
		//android.util.Log.v(tag, msg);
        if (logLevel >= 5) {
            if (Product.mPermissonGrant) {
                log.debug("[" + tag + "] " + msg);
            }
        }
    }

	/**
	 * Log verbose
	 * @param tag Tag for this log
	 * @param msg Msg for this log
	 * @param tr Error to serialize in log
	 */
	public static void v(String tag, String msg, Throwable tr) {
		//android.util.Log.v(tag, msg, tr);
        if (logLevel >= 5) {
            if (Product.mPermissonGrant){
                log.debug("[" + tag + "] " + msg + tr.getLocalizedMessage());
            }
        }
    }
	
	/**
	 * Log debug
	 * @param tag Tag for this log
	 * @param msg Msg for this log
	 */
	public static void d(String tag, String msg) {
        //android.util.Log.d(tag, msg);
        if (logLevel >= 4) {
            if (Product.mPermissonGrant) {
                log.debug("[" + tag + "] " + msg);
            }
        }
    }

    public static void debug(Class cls, String str) {
        //android.util.Log.d(cls.getSimpleName(), str);
        if (logLevel >= 4) {
            if (Product.mPermissonGrant) {
                log.debug("[" + cls.getSimpleName() + "] " + str);
            }
        }
    }

	public static void pjsipLog(String str) {
		//android.util.Log.d(cls.getSimpleName(), str);
		if (logLevel >= 4) {
			if (Product.mPermissonGrant) {
				log.debug(str);
				//log.debug(str);
			}
		}
	}

	/**
	 * Log debug
	 * @param tag Tag for this log
	 * @param msg Msg for this log
	 * @param tr Error to serialize in log
	 */
	public static void d(String tag, String msg, Throwable tr) {
        //android.util.Log.d(tag, msg, tr);
        if (logLevel >= 4) {
            if (Product.mPermissonGrant) {
                log.debug("[" + tag + "] " + msg + tr.getLocalizedMessage());
            }
        }
    }
	
	/**
	 * Log info
	 * @param tag Tag for this log
	 * @param msg Msg for this log
	 */
	public static void i(String tag, String msg) {
        //android.util.Log.i(tag, msg);
        if (logLevel >= 3) {
            if (Product.mPermissonGrant) {
                log.info("[" + tag + "] " + msg);
            }
        }
    }

	/**
	 * Log info
	 * @param tag Tag for this log
	 * @param msg Msg for this log
	 * @param tr Error to serialize in log
	 */
	static void i(String tag, String msg, Throwable tr) {
        //android.util.Log.i(tag, msg, tr);
        if (logLevel >= 3) {
            if (Product.mPermissonGrant) {
                log.info("[" + tag + "] " + msg + tr.getLocalizedMessage());
            }
        }
    }

	/**
	 * Log warning
	 * @param tag Tag for this log
	 * @param msg Msg for this log
	 */
	public static void w(String tag, String msg) {
		//android.util.Log.w(tag, msg);
        if (logLevel >= 2) {
            if (Product.mPermissonGrant) {
                log.warn("[" + tag + "] " + msg);
            }
        }
    }

	/**
	 * Log warning
	 * @param tag Tag for this log
	 * @param msg Msg for this log
	 * @param tr Error to serialize in log
	 */
	public static void w(String tag, String msg, Throwable tr) {
		//android.util.Log.w(tag, msg);
        if (logLevel >= 2) {
            if (Product.mPermissonGrant){
                log.warn("[" + tag + "] " + msg + tr.getLocalizedMessage());
            }
        }
    }

	/**
	 * Log error
	 * @param tag Tag for this log
	 * @param msg Msg for this log
	 */
	public static void e(String tag, String msg) {
		//android.util.Log.e(tag, msg);
        if (logLevel >= 1) {
            if (Product.mPermissonGrant) {
                log.error("[" + tag + "] " + msg);
            }
        }
    }

	/**
	 * Log error
	 * @param tag Tag for this log
	 * @param msg Msg for this log
	 * @param tr Error to serialize in log
	 */
	public static void e(String tag, String msg, Throwable tr) {
		//android.util.Log.e(tag, msg, tr);
        if (logLevel >= 1) {
            if (Product.mPermissonGrant) {
                log.error("[" + tag + "] " + msg + tr.getLocalizedMessage());
            }
        }
    }
	
	
	public static void initLog() {

		// WriteLog log = WriteLog.getInstance();
		// log.startLog();
		if(!createLogDir())
		{
			return;
		}

		LogConfigurator logConfigurator = new LogConfigurator();

		logConfigurator.setFileName(Environment.getExternalStorageDirectory()
				+ File.separator + "CloudPTT" + File.separator + "logs"
				+ File.separator + "pttlog.txt");

		logConfigurator.setRootLevel(Level.DEBUG);
		logConfigurator.setLevel("org.apache", Level.ERROR);
		logConfigurator.setFilePattern("%d %-5p %m%n");
		logConfigurator.setMaxFileSize(1024 * 1024 * 2);
		logConfigurator.setMaxBackupSize(50);
		logConfigurator.setImmediateFlush(true);
		logConfigurator.configure();

		String brand = android.os.Build.BRAND;
		String device = android.os.Build.DEVICE;
		String model = android.os.Build.MODEL;
//		if(PNC460.isThisDev(brand,device,model)
//				|| PNC550.isThisDev(brand,device,model)
//				|| PNC560.isThisDev(brand,device,model))
//		{
//
//			setDebug(false);
//		}
//		else
		{
			setDebug(true);
		}
	}

	public static boolean isDebug() {
		Log.e(THIS_FILE,"isDebug logLevel = " + logLevel);
		if(logLevel >= 6)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	public static void setDebug(boolean isDebug) {
		Log.e(THIS_FILE,"setDebug isDebug = " + isDebug);
		isDebug = isDebug;
		if(isDebug)
		{
			setLogLevel(6);
		}
		else
		{
			setLogLevel(2); /* TODO: 暂时都设置为debug，方便定位问题 */
		}
		Log.e(THIS_FILE,"setDebug logLevel = " + logLevel);
	}
	
	/**
	 * make the dir
	 */
	public static boolean createLogDir() {
		File file;
		boolean mkOk = false;
		if(!Product.mPermissonGrant){
			return mkOk;
		}

		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			file = new File(Environment.getExternalStorageDirectory()
					+ File.separator + "CloudPTT" + File.separator + "logs");

			try {
				if (!file.isDirectory()) {
					mkOk = file.mkdirs();
					if (!mkOk) {
						mkOk = true;
					}
				}
				else
				{
					mkOk = true;
				}
			} catch (Exception e) {
				
			}
		}
		return mkOk;
	}
	public static void printStackTrace(Throwable e) {
		e.printStackTrace();
    }
}
